<?php

namespace IDock\Insurance\MACN\Response;

use IDock\Http\Response;
use IDock\IDock\IDockEnums;
use IDock\Insurance\MACN\MACNEnums;
use IDock\Printer\Premium\PremiumBIPrinter;
use IDock\Printer\Premium\PremiumCIPrinter;
use IDock\Printer\Premium\PremiumCoveragePrinter;
use IDock\Printer\Premium\PremiumFactorPrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\Premium\PremiumTaxPrinter;

class PremiumInquiryResponse extends AllMACNResponse
{
    public function resolve(): Response
    {
        $body = $this->getBody();
        $body = iconv('UTF-8', 'GBK', $body);
        if ($body) {
            libxml_disable_entity_loader();
            $body = simplexml_load_string($body);
            $body = $this->objectToArray($body);
            $errorCode = $body['head']['statusCode'] ?? '';
            $this->setBody($body['body'] ?? '');
            $this->printer = new PremiumInquiryPrinter();
            if ($errorCode !== 'success' && $errorCode !== '000000') {
                $this->printer->success = false;
                $this->getRepeatData($body['body']['proposalInfo'] ?? '');

                if (!$this->printer->repeatInsuredFlg) {
                    $this->setError($body['head']['description'] ?? '未知错误或无错误提示');
                } else {
                    $error = ($body['head']['description']) . "\r\n". ($body['body']['proposalInfo']['reMsg'] ?? '');
                    $this->printer->repeatMessage = $error;
                }

                return $this;
            }
        }

        return $this;
    }

    public function printerInit(): Response
    {
        if (!$this->printer->success) {
            return $this;
        }

        $premiumInquiryPrinter = $this->printer;
        $premiumInquiryPrinter->success = true;
        $data = $this->getBody();

        $reMsg = $data['proposalInfo']['reMsg'] ?? '';
        $this->getRepeatData($data['proposalInfo'] ?? '');

        if ($premiumInquiryPrinter->repeatInsuredFlg) {
            $premiumInquiryPrinter->success = false;
            $premiumInquiryPrinter->repeatMessage = $reMsg;
            $this->printer = $premiumInquiryPrinter;
            return $this;
        }
        $jqData = $data['forceRiskInfo'] ?? [];
        //交强险
        $premiumInquiryPrinter->inquiryNo = $data['baseInfo']['preProposalTopNo'] ?? '';//总询价单号
        $premiumInquiryPrinter->ciInquiryNo = $data['baseInfo']['bizProposalNo'] ?? '';
        $premiumInquiryPrinter->biInquiryNo = $data['baseInfo']['efcProposalNo'] ?? '';
        $premiumInquiryPrinter->argc['askCalcNo'] = $data['baseInfo']['askCalcNo'] ?? '';
        $premiumInquiryPrinter->argc['preProposalTopNo'] = $data['baseInfo']['preProposalTopNo'] ?? '';
        $premiumInquiryPrinter->argc['frameNo'] = $data['itemInfo']['frameNo'] ?? '';

        $ciPremiumPrinter = new PremiumCIPrinter();
        $ciPremiumPrinter->ciPremium = $jqData['itemKindInfo']['discountSumPremium'] ?? '';//交强险保费
        $ciPremiumPrinter->ciStartData = $jqData['startDate'] ?? '';//交强险起保日期
        if(!empty($ciPremiumPrinter->ciStartData)){
            $ciPremiumPrinter->ciStartData = ($jqData['startDate'] . ' ' . ($jqData['startTime'] ?? '') . ':00');
        }
        $ciPremiumPrinter->ciEndData = $jqData['endDate'] ?? '' ;//交强险终保日期
        if($ciPremiumPrinter->ciEndData){
            $ciPremiumPrinter->ciEndData = ($jqData['endDate'] . ' ' . ($jqData['endTime'] ?? '') . ':00');
        }
        $ciPremiumPrinter->ciBasePremium = $jqData['itemKindInfo']['sumPremium'] ?? '0';//交强险保费（不含增值税）
        $ciPremiumPrinter->ciDiscount = round(($jqData['itemKindInfo']['discount'] ?? 0) / 100, 2) ?? '1';//交强折扣率
        $premiumInquiryPrinter->ciPremiumPrinter = $ciPremiumPrinter;

        $carTaxPrinter = new PremiumTaxPrinter();
        $carTaxPrinter->carShipTax = $jqData['carShipTaxInfo']['sumPayTax'] ?? 0;
        $carTaxPrinter->thisYearTax = $jqData['carShipTaxInfo']['taxDueActual'] ?? 0;//本年应缴税
        $carTaxPrinter->overdue = $jqData['carShipTaxInfo']['lateFee'] ?? 0;
        $carTaxPrinter->payBackTax = $data['carShipTaxInfo']['previousPay'] ?? 0;
        $premiumInquiryPrinter->carTaxPrinter = $carTaxPrinter;

        $biData = $data['businessRiskInfo'] ?? '';

        $biPremiumPrinter = new PremiumBIPrinter();
        $biPremiumPrinter->biPremium = $biData['bizSumCharge'] ?? '';//商业险保费
        $biPremiumPrinter->biStartData = $biData['startDate'] ?? '';//商业险起保日期
        if($biPremiumPrinter->biStartData){
            $biPremiumPrinter->biStartData = ($biData['startDate'] . ' ' . ($biData['startTime'] ?? '') . ':00');
        }
        $biPremiumPrinter->biEndData = $biData['endDate'] ?? '';//商业险终保日期
        if($biPremiumPrinter->biEndData){
            $biPremiumPrinter->biEndData = ($biData['endDate'] . ' ' . ($biData['endTime'] ?? '') . ':00');
        }
        $biPremiumPrinter->biBasePremium = 0;//商业险基础保费
        $premiumInquiryPrinter->biPremiumPrinter = $biPremiumPrinter;

        $coverageList = $biData['itemKindList']['itemKindInfo'] ?? [];
        $biBasePremium = 0;
        $discount = 0;
        if (!empty($coverageList)) {
            if (!isset($coverageList[0])) {
                $tmp = $coverageList;
                unset($coverageList);
                $coverageList[0] = $tmp;
            }
            foreach ($coverageList as $row) {
                $coverage = new PremiumCoveragePrinter();
                $coverage->coverageCode = array_search($row['kindCode'], MACNEnums::$coverageCode);
                $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode];
                $coverage->amount = $row['sumInsured'] ?? 0;
                $coverage->premium = $row['discountSumPremium'] ?? 0;
                $coverage->basePremium = $row['sumPremium'] ?? 0;
                $coverage->discount = round(($row['discount'] ?? 0) / 100,4);
                $biBasePremium += floatval($coverage->basePremium);
                $coverage->serviceTimes = $row['quantity'] ?? '0';
                $premiumInquiryPrinter->coverageListAppend($coverage);
                $discount = $coverage->discount;
            }
        }

        $premiumInquiryPrinter->biPremiumPrinter->biDiscount = $discount;
        $premiumInquiryPrinter->biPremiumPrinter->biBasePremium = $biBasePremium;
        //特约
        //交商系数
        $riskRatio = $data['proposalInfo'] ?? [];
        $premiumInquiryPrinter->ncdFactor = $riskRatio['claimAdjustLevel'] ?? '';
        $factorPrinter = new PremiumFactorPrinter();
        $factorPrinter->ComFactorAppend('业务品质总评分', 'businessquality', $riskRatio['businessquality'] ?? '');
        $factorPrinter->ComFactorAppend('商业险理赔浮动原因', 'bizLastPolicyNum', $riskRatio['claimAdjustReasonBI'] ?? '');
        $factorPrinter->ComFactorAppend('交强险理赔浮动原因', 'efcLastPolicyNum', $riskRatio['claimAdjustReasonCI'] ?? '');
        $factorPrinter->ComFactorAppend('车慧达分档', 'MACNPriTranche', $riskRatio['priTranche'] ?? '');
        $factorPrinter->ComFactorAppend('车慧达分数', 'MACNPriScore', $riskRatio['priScore'] ?? '');
        $factorPrinter->ComFactorAppend('连续承保年数', 'biInsureYears', $riskRatio['insureYears'] ?? '');
        $factorPrinter->ComFactorAppend('无赔优系数级别', 'ncdRate', $riskRatio['claimAdjustLevel'] ?? '');
        $factorPrinter->ComFactorAppend('亚太分', 'ytScore', $riskRatio['ytScore'] ?? '');
        if(!empty($riskRatio['businessTypeCI'])){
            $factorPrinter->ComFactorAppend('交强忠诚度', 'CIRenewalType', $this->getRenewalType($riskRatio['businessTypeCI']));

        }
        if(!empty($riskRatio['businessTypeBI'])){
            $factorPrinter->ComFactorAppend('商业忠诚度', 'BIRenewalType', $this->getRenewalType($riskRatio['businessTypeBI']));

        }
        $premiumInquiryPrinter->premiumFactorPrinter = $factorPrinter;
        $this->printer = $premiumInquiryPrinter;
        return $this;
    }

    private function getRenewalType($typeCode)
    {
        switch ($typeCode){
            case 0:
                return '新';
            case 1:
                return '续';
            case 2:
                return '转';
        }
        return '';
    }

    /**
     * 重复投保
     * @param $data
     */
    public function getRepeatData($data)
    {
        $ciMeg = $data['reMsg'] ?? '';

        if (preg_match('/商业险.*终保日期:([\d\s:-]+)/', $ciMeg, $matches)) {
            if ($matches[1] ?? '') {
                $biStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $this->printer->repeatInsuredFlg = true;
                $this->printer->repeatInsurePrinter['biStartData'] = $biStartData;
            }

            if (isset($data['lastYearStartDateBI']) and $data['lastYearStartDateBI'] and strpos($ciMeg, '重复投保') !== false) {
                $this->printer->repeatInsuredFlg = true;
                $this->printer->repeatInsurePrinter['biStartData'] = $data['lastYearEndDateBI'];
            }
        }

        if (preg_match('/交强险.*重复投保/', $ciMeg, $matches)) {
            $this->printer->repeatInsuredFlg = true;

            if (isset($data['lastYearStartDateCI']) and $data['lastYearStartDateCI'] and strpos($ciMeg, '重复投保') !== false) {
                $this->printer->repeatInsurePrinter['ciStartData'] = $data['lastYearEndDateCI'];
            }
        }
    }

    /**
     * 转新能源险种代码
     * @param $isNewEnergy
     * @return void
     */
    public function transfer($isNewEnergy)
    {
        if ($isNewEnergy) {
            /**
             * @var PremiumCoveragePrinter $value
             */
            foreach ($this->printer->coverageList as $value) {
                $value->coverageCode = str_replace('C0', 'C1', $value->coverageCode);
            }
        }
    }
}
